import OrderDetailModal from '@/components/OrderDetailModal';
import { removeRule } from '@/services/ant-design-pro/api';
import { createProductCategory, updateProductCategory } from '@/services/ant-design-pro/product';
import { deleteTrade, getTradeList } from '@/services/order';
import type { ActionType, ProColumns, ProDescriptionsItemProps } from '@ant-design/pro-components';
import {
  ModalForm,
  PageContainer,
  ProDescriptions,
  ProFormDigit,
  ProFormText,
  ProTable,
  useDebounceFn,
} from '@ant-design/pro-components';
import { Button, Col, Drawer, Input, message, Popconfirm, Row, Tag } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { history, Link } from '@umijs/max';

/**
 * @en-US Add node
 * @zh-CN 添加节点
 * @param fields
 */
const handleAdd = async (fields: API.RuleListItem) => {
  const hide = message.loading('正在添加');
  try {
    await createProductCategory({ status: 1, ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败，请重试。');
    return false;
  }
};

/**
 * @en-US Update node
 * @zh-CN 更新节点
 *
 * @param fields
 */
const handleUpdate = async (fields) => {
  const hide = message.loading('更新中');
  try {
    await updateProductCategory({ ...fields });
    hide();

    message.success('编辑成功');
    return true;
  } catch (error) {
    hide();
    message.error('编辑失败');
    return false;
  }
};

/**
 *  Delete node
 * @zh-CN 删除节点
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows: API.RuleListItem[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    await removeRule({
      key: selectedRows.map((row) => row.key),
    });
    hide();
    message.success('Deleted successfully and will refresh soon');
    return true;
  } catch (error) {
    hide();
    message.error('Delete failed, please try again');
    return false;
  }
};

const TableList: React.FC = () => {
  const [dataSource, setDataSource] = useState([]);
  const [areaList, setAreaList] = useState([]);
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);
  const [detailOrderId, setDetailOrderId] = useState<number | null>(null);
  const [searchParams, setSearchParams] = useState({});

  const [showDetail, setShowDetail] = useState<boolean>(false);
  const [total, setTotal] = useState(0);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.RuleListItem>();

  const columns: ProColumns<API.RuleListItem>[] = [
    {
      search: false,
      title: '订单号',
      dataIndex: 'no',
    },
    {
      search: false,
      title: '创建时间',
      dataIndex: 'createdAt',
    },
    {
      search: false,
      title: '更新时间',
      dataIndex: 'updatedAt',
    },
    {
      search: false,
      title: '交易金额',
      dataIndex: 'payment',
      render: (_, record) => {
        return (
          <div>
            <div>原价：￥{_.originAmount}</div>
            <div>调整：￥{_.adjust}</div>
            <div>折扣：￥{_.discount}</div>
            <div>实际支付：￥{_.amount}</div>
          </div>
        );
      },
    },
    {
      search: false,
      title: '状态',
      dataIndex: 'status',
      valueEnum: {
        0: <Tag color="red">已取消</Tag>,
        1: <Tag>待支付</Tag>,
        2: <Tag color="blue">已完成</Tag>,
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: '220px',
      render: (_, record) => (
        <Row gutter={[10, 10]} className="flex-wrap">
          <Col>
            <Button
              onClick={() => {
                // setDetailOrderId(record.id);
                // setCurrentRow({ ...record, tableNo: record.name });
                history.push(`/order/detail/${record.id}`);
              }}
              type="primary"
            >
              详情
            </Button>
          </Col>

          <Col>
            <Popconfirm
              title="确认完成吗"
              key="delete"
              onConfirm={async () => {
                await deleteTrade(record.id);
                init();
              }}
            >
              <Button type="primary" danger>
                删除
              </Button>
            </Popconfirm>
          </Col>

          {/* <Col>
            <Button
              onClick={() => {
                setCurrentRow({ ...record, tableNo: record.name });
              }}
              type="primary"
              danger
            >
              修改
            </Button>
          </Col> */}

          {/* <Col>
            <Popconfirm
              title="确认取消吗"
              key="delete"
              onConfirm={async () => {
                await cancelTrade(record.id);
                init();
              }}
            >
              <Button type="primary" danger>
                取消
              </Button>
            </Popconfirm>
          </Col>

          <Col>
            <Button
              onClick={async () => {
                await printCashierTicket(record.id);
                init();
              }}
              type="primary"
            >
              打印小票
            </Button>
          </Col> */}
        </Row>
      ),
    },
  ];

  const init = async (params = {}, page = 1) => {
    const resp = await getTradeList({ ...params, page, pageSize: 20 });

    const { list = [], pagination } = resp?.data || {};
    setDataSource(list);
    setTotal(pagination?.total);
  };

  const { run: handleSearch } = useDebounceFn((params) => {
    setSearchParams({ ...searchParams, ...params });
    return init({ ...searchParams, ...params });
  }, 500);

  useEffect(() => {
    init();
  }, []);

  return (
    <PageContainer>
      <OrderDetailModal
        orderId={detailOrderId}
        onCancel={() => {
          setDetailOrderId(null);
        }}
      ></OrderDetailModal>

      <ProTable<API.RuleListItem, API.PageParams>
        actionRef={actionRef}
        rowKey="key"
        search={false}
        pagination={{
          onChange: (page) => {
            console.log('😈page', page);
            init({}, page);
          },
          total,
        }}
        toolbar={{
          search: (
            <Row gutter={10}>
              <Col>
                <Input
                  placeholder="请输入订单号"
                  onChange={(e) => {
                    handleSearch({
                      keyword: e.target.value,
                    });
                  }}
                ></Input>
              </Col>
              {/* <Col>
                <Select
                  style={{ width: '170px' }}
                  options={collectionOptions}
                  allowClear
                  onChange={(value) => {
                    handleSearch({
                      category: value,
                    });
                  }}
                  placeholder="可筛选商品分类"
                ></Select>
              </Col>
              <Col>
                <Select
                  style={{ width: '170px' }}
                  options={[
                    {
                      label: '上架',
                      value: 1,
                    },
                    {
                      label: '下架',
                      value: 0,
                    },
                  ]}
                  allowClear
                  onChange={(value) => {
                    handleSearch({
                      status: value,
                    });
                  }}
                  placeholder="可筛选上下架"
                ></Select>
              </Col> */}
            </Row>
          ),
        }}
        // eslint-disable-next-line react/jsx-key
        toolBarRender={() => [<h4 className="mt10 bold">* 请到点餐台进行下单</h4>]}
        dataSource={dataSource}
        columns={columns}
        // rowSelection={{
        //   onChange: (_, selectedRows) => {
        //     setSelectedRows(selectedRows);
        //   },
        // }}
        onLoad={init}
        options={false}
      />
      <ModalForm
        title={'新建'}
        width="400px"
        modalProps={{
          destroyOnClose: true,
        }}
        open={createModalOpen}
        onOpenChange={handleModalOpen}
        onFinish={async (value) => {
          const success = await handleAdd(value as API.RuleListItem);
          if (success) {
            handleModalOpen(false);
            init();
          }
        }}
      >
        <ProFormText
          label="分类名称"
          rules={[
            {
              required: true,
            },
          ]}
          name="name"
        />
        <ProFormDigit label="排序" name="sort" />
      </ModalForm>

      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions<API.RuleListItem>
            column={2}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.name,
            }}
            columns={columns as ProDescriptionsItemProps<API.RuleListItem>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
